﻿using System;
using System.Collections.Generic;
using System.Text;

namespace EmbeddedSharp.Core {
    public class FunctionFormExpressionTranslator : IExpressionTranslator {
        #region IExpressionCompiler Members

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public string Translate(EmbeddedSharp.Core.Node node) {
            string expr = this.InternalCompile(node);

            //if (expr.StartsWith("(") && expr.EndsWith(")")) {
            //    expr = expr.Remove(0, 1);
            //    expr = expr.Remove(expr.Length - 1, 1);
            //}

            return expr;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected string InternalCompile(EmbeddedSharp.Core.Node node) {
            string b = string.Empty;
            if (node.GetType().IsSubclassOf(typeof(FuncNode))) {
                FuncNode fn = (FuncNode)node;
                b += fn.Value + "(";
                for (int index = fn.Parameters.Count - 1; index >= 0; index--) {
                    b += this.Translate(fn.Parameters[index]);
                    if (index > 0) {
                        b += ",";
                    }
                }
                b += ")";
            } else {
                b = node.Value;
            }

            return b;
        }

        #endregion
    }
}
